package utils;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class OKHttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(OKHttpUtils.class);

    public static String getPostResponse(String url, String requestBody) throws IOException, Exception {

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)
                .post(RequestBody.create(MediaType.get("application/json"), requestBody))
                .build();
        logger.info("requestUrl: {}, requestBody: {}", url, requestBody);
        Response response = httpClient.newCall(request).execute();
//        logger.info("requestUrl: {}, requestBody: {}, response {}", url, requestBody,response);
        ResponseBody body = response.body();
        String res = body == null ? "" : body.string();
        if (response.isSuccessful()) {
//            logger.info("success:{}", res);
            return res;
        } else {
            logger.error("error,statusCode={},body={}", response.code(), res);
            return null;
        }
    }

    public static boolean getStreamGetResponse(String url, String requestBody, String outputFilePath) throws IOException, Exception {

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)
                .get()
                .header("Content-Type", "application/json")
                .post(RequestBody.create(MediaType.get("application/json"), requestBody))
                .build();

        logger.info("requestUrl: {}, requestBody: {}", url, requestBody);
        Response response = httpClient.newCall(request).execute();

        ResponseBody body = response.body();

        if (response.isSuccessful()) {
            // 使用输入流来读取数据，避免一次性加载整个文件到内存中
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                inputStream = body.byteStream();

                Path path = Paths.get(outputFilePath);
                if (!Files.exists(path)) {
                    try {
                        Files.createFile(path);
                    } catch (IOException e) {
                        logger.error("File create error ", e);
                        // 处理异常，例如输出错误消息或退出程序
                    }
                }
                outputStream = Files.newOutputStream(path);
//                outputStream = new TarArchiveOutputStream(
//                        new GzipCompressorOutputStream(
//                                new BufferedOutputStream(
//                                        Files.newOutputStream(path))));
                byte[] buffer = new byte[1024]; // 可以根据需要调整缓冲区大小
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                logger.info("File downloaded and saved at " + outputFilePath);
            } catch (Exception e){
                logger.error("File download error ", e);
                return false;
            } finally {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            }
            return true;
        } else {
            logger.error("error,statusCode={}", response.code());
            return false;
        }

    }

    public static String getFormPostResponse(String url, RequestBody requestBody) throws IOException, Exception {

        OkHttpClient httpClient = new OkHttpClient();

        Request request = new Request
                .Builder()
                .url(url)
                .post(requestBody)
                .build();

        logger.info("requestUrl: {}, requestBody: {}", url, requestBody);
        Response response = httpClient.newCall(request).execute();
        ResponseBody body = response.body();
        String res = body == null ? "" : body.string();
        if (response.isSuccessful()) {
//            logger.info("success:{}", res);
            return res;
        } else {
            logger.error("error,statusCode={},body={}", response.code(), res);
            return null;
        }
    }

}
